package com.itheima.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.service.ShoppingCartService;
import com.itheima.bean.ShoppingCart;
import com.itheima.common.R;
import com.itheima.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    //添加购物车
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){
        ShoppingCart cart = shoppingCartService.add(shoppingCart);
        return R.success(cart);
    }

    //删除购物车
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        ShoppingCart cart=shoppingCartService.update(shoppingCart);
       if (cart==null){
           return R.error("删除错误");
       }
        return R.success(cart);
    }

    //查询当前用户的购物车数据
    @GetMapping("list")
    public R list(){
        //1.构建条件对象
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();

        //2.封装条件
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        //3.执行查询
        List<ShoppingCart> list = shoppingCartService.list(lqw);

        //4.返回结果
        return R.success(list);
    }

    //清空当前用户的购物车数据
    @DeleteMapping("/clean")
    public R clean(){
        //1.构建条件对象
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();

        //2.封装条件
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        //3.执行删除
        boolean result = shoppingCartService.remove(lqw);

        //3.返回结果
        if(result){
            return R.success("执行删除成功");
        }
        return R.error("执行删除失败");

    }
}

